<template>
	<view style="width: 100vw;">
		<!-- 顶部导航 -->
    <view class="schedule-model-form-container">
      <BoxView :titBoxObj="{
        title: isEditing ? '编辑模式' : '创建模式',
        titleCount: '管理赛程模型配置'
      }" style="width: 70%;background-color: #FFFFF4;">
        <view class="schedule-model-form">
          <view class="form-item">
            <text class="form-label">模式名称 <text class="form-label-required">*</text></text>
            <input 
              class="form-input" 
              v-model="formData.matchScheduleModelName" 
              placeholder="请输入模式名称"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">房间数量</text>
            <input 
              class="form-input" 
              v-model="formData.roomNum" 
              type="number"
              placeholder="0表示自动计算"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">房间类型</text>
            <view class="form-input">
              <view class="form-picker" @click="openRoomTypePicker">
                <text class="picker-text">{{ roomTypeOptions[roomTypeIndex] }}</text>
              </view>
            </view>
          </view>
          
          <view class="form-item" v-if="formData.roomType === 4 || formData.roomType === 5">
            <text class="form-label">房间类型N</text>
            <input 
              class="form-input" 
              v-model="formData.roomTypeN" 
              type="number"
              placeholder="请输入N值"
            />
          </view>
          
          <view class="form-item" v-if="formData.roomType === 5">
            <text class="form-label">房间类型M</text>
            <input 
              class="form-input" 
              v-model="formData.roomTypeM" 
              type="number"
              placeholder="请输入M值"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">启动类型</text>
            <view class="form-input">
              <view class="form-picker" @click="openStartTypePicker">
                <text class="picker-text">{{ startTypeOptions[startTypeIndex] }}</text>
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">参与模式</text>
            <view class="form-input">
              <view class="form-picker" @click="openJoinModelPicker">
                <text class="picker-text">{{ joinModelOptions[joinModelIndex] }}</text>
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">限制模式</text>
            <view class="form-input">
              <view class="form-picker" @click="openLimitModelPicker">
                <text class="picker-text">{{ limitModelOptions[limitModelIndex] }}</text>
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">获胜模式</text>
            <view class="form-input">
              <view class="form-picker" @click="openWinModelPicker">
                <text class="picker-text">{{ winModelOptions[winModelIndex] }}</text>
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">报名模式</text>
            <view class="form-input">
              <view class="form-picker" @click="openRegTypePicker">
                <text class="picker-text">{{ regTypeOptions[regTypeIndex] }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="schedule-model-form-button">
          <view class="submit-btn" @click="submitForm" :disabled="submitting">
            {{ submitting ? '提交中...' : (isEditing ? '保存修改' : '创建模式') }}
          </view>
          <view class="cancel-btn" @click="goBack">取消</view>
        </view>
      </BoxView>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
    
    <!-- 房间类型选择弹出框 -->
    <PopuleView
      v-model="showRoomTypePicker"
      title="选择房间类型"
      :list-data="roomTypeOptions.map((opt, idx) => ({ id: idx, label: opt }))"
      :selected-value="roomTypeIndex"
      :show-submit="false"
      item-label="label"
      item-key="id"
      @item-click="(item, index) => selectRoomType(item)"
    />
    
    <!-- 启动类型选择弹出框 -->
    <PopuleView
      v-model="showStartTypePicker"
      title="选择启动类型"
      :list-data="startTypeOptions.map((opt, idx) => ({ id: idx, label: opt }))"
      :selected-value="startTypeIndex"
      :show-submit="false"
      item-label="label"
      item-key="id"
      @item-click="(item, index) => selectStartType(item)"
    />
    
    <!-- 参与模式选择弹出框 -->
    <PopuleView
      v-model="showJoinModelPicker"
      title="选择参与模式"
      :list-data="joinModelOptions.map((opt, idx) => ({ id: idx, label: opt }))"
      :selected-value="joinModelIndex"
      :show-submit="false"
      item-label="label"
      item-key="id"
      @item-click="(item, index) => selectJoinModel(item)"
    />
    
    <!-- 限制模式选择弹出框 -->
    <PopuleView
      v-model="showLimitModelPicker"
      title="选择限制模式"
      :list-data="limitModelOptions.map((opt, idx) => ({ id: idx, label: opt }))"
      :selected-value="limitModelIndex"
      :show-submit="false"
      item-label="label"
      item-key="id"
      @item-click="(item, index) => selectLimitModel(item)"
    />
    
    <!-- 获胜模式选择弹出框 -->
    <PopuleView
      v-model="showWinModelPicker"
      title="选择获胜模式"
      :list-data="winModelOptions.map((opt, idx) => ({ id: idx, label: opt }))"
      :selected-value="winModelIndex"
      :show-submit="false"
      item-label="label"
      item-key="id"
      @item-click="(item, index) => selectWinModel(item)"
    />
    
    <!-- 报名模式选择弹出框 -->
    <PopuleView
      v-model="showRegTypePicker"
      title="选择报名模式"
      :list-data="regTypeOptions.map((opt, idx) => ({ id: idx, label: opt }))"
      :selected-value="regTypeIndex"
      :show-submit="false"
      item-label="label"
      item-key="id"
      @item-click="(item, index) => selectRegType(item)"
    />
	</view>
</template>

<script setup>
import { ref, computed, nextTick, onBeforeUnmount, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchScheduleModelAPI } from '@/api/battle.js'
import TopNavigation from "@/components/UiView/TopNavigation.vue";
import BackgroundImage from "@/components/BackgroundImage.vue";
import BoxView from "@/components/UiView/BoxView.vue";
import PopuleView from "@/components/UiView/PopuleView.vue";

// 定义 emit
const emit = defineEmits(['close'])

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const isEditing = ref(false)
const modelId = ref('')

// 选择器相关数据
const showRoomTypePicker = ref(false)
const showStartTypePicker = ref(false)
const showJoinModelPicker = ref(false)
const showLimitModelPicker = ref(false)
const showWinModelPicker = ref(false)
const showRegTypePicker = ref(false)

// 选择器索引
const roomTypeIndex = ref(2)
const startTypeIndex = ref(1)
const joinModelIndex = ref(1)
const limitModelIndex = ref(0)
const winModelIndex = ref(2)
const regTypeIndex = ref(0)

// 表单数据
const formData = ref({
  matchScheduleModelName: '',
  matchScheduleModelId: '',
  roomNum: 0,
  roomType: 2,
  roomTypeN: 0,
  roomTypeM: 0,
  roomStartType: 1,
  roomCreateModel: 0,
  roomJoinModel: 1,
  roomLimitModel: 0,
  matchModel: 0,
  matchRegType: 0,
  matchWinModel: 3
})

// 选项数据
const roomTypeOptions = [
  'N对N 2组', '单人 1组', '1对1 2组', '2对2 2组', '单人多组 N组', '多人多组 N组'
]
const startTypeOptions = ['定时开赛', '手动开赛', '人满即开']
const joinModelOptions = ['主动进入', '随机', '参考房间限制模式', '等级水平']
const limitModelOptions = ['无限制', '水平 1-2之间', '水平 2-3之间']
const winModelOptions = [
  '一回合 抢1分', '三回合 抢2分', '五回合 抢3分', '高分', 'BO3', 
  'AO5', 'BAO5', '时间短', '步数短', '距离长', '五局（抢3） 五回合（抢3）'
]
const regTypeOptions = ['先报名', '预报名', '后报名', '自定义']

// 加载编辑数据（从全局存储）
const loadEditData = async () => {
  try {
    console.log('开始加载编辑数据...')
    const editData = uni.getStorageSync('editScheduleModelData')
    console.log('读取到的编辑数据:', editData)
    
    if (editData) {
      const data = typeof editData === 'string' ? JSON.parse(editData) : editData
      console.log('解析后的编辑数据:', data)
      
      isEditing.value = true
      modelId.value = data.id || data.matchScheduleModelId
      
      // 填充表单数据
      formData.value = {
        matchScheduleModelName: data.matchScheduleModelName || '',
        matchScheduleModelId: data.matchScheduleModelId || data.id || '',
        roomNum: data.roomNum || 0,
        roomType: data.roomType !== undefined ? data.roomType : 2,
        roomTypeN: data.roomTypeN || 0,
        roomTypeM: data.roomTypeM || 0,
        roomStartType: data.roomStartType !== undefined ? data.roomStartType : 1,
        roomCreateModel: data.roomCreateModel || 0,
        roomJoinModel: data.roomJoinModel !== undefined ? data.roomJoinModel : 1,
        roomLimitModel: data.roomLimitModel !== undefined ? data.roomLimitModel : 0,
        matchModel: data.matchModel || 0,
        matchRegType: data.matchRegType !== undefined ? data.matchRegType : 0,
        matchWinModel: data.matchWinModel !== undefined ? data.matchWinModel : 3
      }
      
      // 设置选择器索引
      roomTypeIndex.value = formData.value.roomType
      startTypeIndex.value = formData.value.roomStartType
      joinModelIndex.value = formData.value.roomJoinModel
      limitModelIndex.value = formData.value.roomLimitModel
      winModelIndex.value = (formData.value.matchWinModel || 3) - 1
      regTypeIndex.value = formData.value.matchRegType
      
      console.log('编辑数据加载完成')
    } else {
      console.log('未找到编辑数据，使用创建模式')
    }
  } catch (error) {
    console.error('加载编辑数据失败:', error)
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    })
  }
}

// 加载模式数据（编辑模式，通过API）
const loadModelData = async () => {
  if (!modelId.value) return
  
  loading.value = true
  try {
    const result = await MatchScheduleModelAPI.page({
      matchScheduleModelId: modelId.value,
      pageNum: 0,
      pageSize: 1
    })
    
    if (result.code === 0 && result.data) {
      const modelList = result.data.list || result.data || []
      if (modelList.length > 0) {
        const model = modelList[0]
        formData.value = { ...model }
        if (model.id && !model.matchScheduleModelId) {
          formData.value.matchScheduleModelId = model.id
        }
        
        // 设置选择器索引
        roomTypeIndex.value = model.roomType || 2
        startTypeIndex.value = model.roomStartType || 1
        joinModelIndex.value = model.roomJoinModel || 1
        limitModelIndex.value = model.roomLimitModel || 0
        winModelIndex.value = (model.matchWinModel || 3) - 1
        regTypeIndex.value = model.matchRegType || 0
      }
    }
  } catch (error) {
    console.error('加载模式数据失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 页面加载
onLoad((options) => {
  console.log('bindle页面加载，参数:', options)
  
  // 优先从全局存储读取编辑数据（不通过链接传递）
  loadEditData()
  
  // 兼容旧的URL参数方式
  if (options.mode === 'edit' && options.id && !isEditing.value) {
    isEditing.value = true
    modelId.value = options.id
    loadModelData()
  }
})

// 返回上一页
const goBack = () => {
  // 清除编辑数据
  uni.removeStorageSync('editScheduleModelData')
  // 触发关闭事件，通知父组件
  emit('close')
}

// 选择器打开和关闭函数
const openRoomTypePicker = () => {
  showRoomTypePicker.value = true
}

const selectRoomType = (item) => {
  const index = typeof item === 'object' ? item.id : item
  roomTypeIndex.value = index
  formData.value.roomType = index
  showRoomTypePicker.value = false
}

const openStartTypePicker = () => {
  showStartTypePicker.value = true
}

const selectStartType = (item) => {
  const index = typeof item === 'object' ? item.id : item
  startTypeIndex.value = index
  formData.value.roomStartType = index
  showStartTypePicker.value = false
}

const openJoinModelPicker = () => {
  showJoinModelPicker.value = true
}

const selectJoinModel = (item) => {
  const index = typeof item === 'object' ? item.id : item
  joinModelIndex.value = index
  formData.value.roomJoinModel = index
  showJoinModelPicker.value = false
}

const openLimitModelPicker = () => {
  showLimitModelPicker.value = true
}

const selectLimitModel = (item) => {
  const index = typeof item === 'object' ? item.id : item
  limitModelIndex.value = index
  formData.value.roomLimitModel = index
  showLimitModelPicker.value = false
}

const openWinModelPicker = () => {
  showWinModelPicker.value = true
}

const selectWinModel = (item) => {
  const index = typeof item === 'object' ? item.id : item
  winModelIndex.value = index
  formData.value.matchWinModel = index + 1
  showWinModelPicker.value = false
}

const openRegTypePicker = () => {
  showRegTypePicker.value = true
}

const selectRegType = (item) => {
  const index = typeof item === 'object' ? item.id : item
  regTypeIndex.value = index
  formData.value.matchRegType = index
  showRegTypePicker.value = false
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.matchScheduleModelName.trim()) {
    uni.showToast({
      title: '请输入模式名称',
      icon: 'none'
    })
    return
  }
  
  if (formData.value.roomType === 4 || formData.value.roomType === 5) {
    if (!formData.value.roomTypeN || formData.value.roomTypeN <= 0) {
      uni.showToast({
        title: '请输入有效的房间类型N值',
        icon: 'none'
      })
      return
    }
  }
  
  if (formData.value.roomType === 5) {
    if (!formData.value.roomTypeM || formData.value.roomTypeM <= 0) {
      uni.showToast({
        title: '请输入有效的房间类型M值',
        icon: 'none'
      })
      return
    }
  }
  
  submitting.value = true
  try {
    const api = isEditing.value ? MatchScheduleModelAPI.edit : MatchScheduleModelAPI.create
    
    const submitData = { ...formData.value }
    
    if (isEditing.value) {
      submitData.matchScheduleModelId = formData.value.matchScheduleModelId || formData.value.id || modelId.value
    }
    
    const result = await api(submitData)
    
    if (result.code === 0) {
      uni.showToast({
        title: isEditing.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      
      // 设置刷新标记
      uni.setStorageSync('scheduleModelListNeedRefresh', true)
      
      // 延迟关闭，让用户看到成功提示
      setTimeout(() => {
        goBack()
      }, 1500)
    } else {
      throw new Error(result.msg || (isEditing.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({
      title: error.message || (isEditing.value ? '更新失败' : '创建失败'),
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 页面卸载时清除编辑数据
onBeforeUnmount(() => {
  uni.removeStorageSync('editScheduleModelData')
})
</script>

<style lang="scss" scoped>
.schedule-model-form-container {
  height: calc(100vh - 70rpx);
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-bottom: 10rpx;
}

.schedule-model-form {
  background-color: #F0F0E4;
  overflow: auto;
  border-radius: 10rpx;
  margin: 10rpx;
  margin-bottom: 5rpx;
  padding: 10rpx;
  height: calc(100% - 100rpx);

  .form-item {
    display: flex;
    align-items: start;
    margin-bottom: 10rpx;

    .form-label {
      font-size: 14rpx;
      width: 100rpx;
      text-align: right;
      color: #333;

      .form-label-required {
        color: orangered;
      }
    }

    .form-input {
      margin-left: 10rpx;
      height: 26rpx;
      line-height: 26rpx;
      padding: 0 10rpx;
      font-size: 13rpx;
      color: #000000;
      background-color: #DADADA;
      border-radius: 4rpx;
      width: 60%;
      box-sizing: border-box;
      
      .form-picker {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        
        .picker-text {
          font-size: 13rpx;
          color: #000000;
        }
      }
    }
  }
}

.schedule-model-form-button {
  display: flex;
  justify-content: center;
  align-items: center;

  view {
    height: 30rpx;
    width: 118rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14rpx;
  }

  .submit-btn {
    color: #FFFFFF;
    background: url('/static/buttons/button6.png') no-repeat center center;
    background-size: 100% 100%;
  }

  .cancel-btn {
    background: url('/static/buttons/button7.png') no-repeat center center;
    background-size: 100% 100%;
    color: #FFFFFF;
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .loading-content {
    background: #fff;
    border-radius: 20rpx;
    padding: 60rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

